package cn.topcodes.tcsf.app.service.impl;

import cn.topcode.unicorn.utils.DateUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.app.domain.entity.AppClient;
import cn.topcodes.tcsf.app.domain.entity.DailyActiveUsers;
import cn.topcodes.tcsf.app.service.DailyActiveUsersService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * Created by Unicorn on 2018/1/8.
 */
@Service
public class DailyActiveUsersServiceImpl extends GenericService<DailyActiveUsers> implements DailyActiveUsersService {

    /**
     * 记录用户活跃
     * @param app
     * @param appUserId
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void record(String app, Long appUserId) {
        Assert.notNull(appUserId, "app用户ID不能为空");
        Example example = this.buildExample();
        Example.Criteria criteria = example.createCriteria();
        Date date = DateUtil.change0H0M0S(new Date());
        criteria.andEqualTo(DailyActiveUsers.FIELD_DAU_DATE, date);
        criteria.andEqualTo(DailyActiveUsers.FIELD_APP_USER_ID, appUserId);
        if(StringUtil.isNotBlank(app)) {
            criteria.andEqualTo(DailyActiveUsers.FIELD_APP, app);
        }
        DailyActiveUsers dau = this.findOne(example);
        if(dau == null) {
            dau = new DailyActiveUsers();
            dau.setApp(app);
            dau.setAppUserId(appUserId);
            dau.setDauDate(date);
            dau.setCount(1);
            this.save(dau);
        }
    }

    /**
     * 记录用户活跃
     * @param appUserId
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void record(Long appUserId) {
        this.record(AppClient.APP_DEFAULT, appUserId);
    }

    /**
     * 查询用户在指定时段的活跃情况
     *
     * @param appUserId app用户ID
     * @param start     开始时间
     * @param end       结束时间
     * @return
     */
    @Override
    public List<DailyActiveUsers> findBy(Long appUserId, Date start, Date end) {
        Example example = this.buildExample();
        Example.Criteria criteria = example.createCriteria();
        if(appUserId != null) {
            criteria.andEqualTo(DailyActiveUsers.FIELD_APP_USER_ID, appUserId);
        }
        if(start != null) {
            criteria.andGreaterThanOrEqualTo(DailyActiveUsers.FIELD_DAU_DATE, start);
        }
        if(end != null) {
            criteria.andLessThanOrEqualTo(DailyActiveUsers.FIELD_DAU_DATE, end);
        }
        return this.findAll(example);
    }
}
